<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="../../assets/libs/layui/css/layui.css"/>
    <link rel="stylesheet" href="../../assets/css/article-preview.css">
    <link rel="stylesheet" href="../../assets/css/article-detail.css">
    <link rel="stylesheet" href="../../assets/iconfont/iconfont.css">
</head>
<body>
<div id="article-preview" class="blog-content-box">
    <div class="blog-haeder">
        <div class="blog-info-title"></div>
        <div class="blog-article-info">
            <div class="blog-top-bar">
                <span class="layui-badge blog-info-type"></span>
                <span class="blog-info-author"></span>
                <span class=blog-info-createTime> </span>
                <span class="blog-info-hits"> <i class="icon-chakan iconfont"></i>&nbsp;</span>
                <span class="blog-info-collect"> <i class="icon-shoucang iconfont"></i>&nbsp;</span>
            </div>
            <div class="blog-tag">
                <span class="blog-info-category">分类专栏：</span>
                <span class="blog-info-tags">文章标签：</span>
            </div>
        </div>
    </div>
    <div class="content-wrap">
        <div id="content" class="content">
            <div id="posts" class="posts-expand">
                <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
                    <div class="post-block" style="opacity: 1; display: block;">
                        <div class="blog-info-content post-body" itemprop="articleBody"
                             style="opacity: 1; display: block; transform: translateY(0px);"></div>
                    </div>
                </article>
            </div>
        </div>
    </div>
    <div class="comments" id="comments" style="opacity: 1; display: block;">
        <div id="comments-content" class="segment">
            <h3 class="dividing">评论</h3>

        </div>
        <div class="comment-form layui-form" id="jump_comment" lay-filter="comment-form">
            <div id="blogEditor"></div>
            <button type="button" class="layui-btn layui-btn-primary" lay-submit lay-filter="submitCommnet">提交评论
            </button>
        </div>
        <div id="view"></div>
    </div>
</div>
</body>
<script type="text/javascript" src="../../assets/libs/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="../../assets/libs/layui/layui.js"></script>
<script id="comment_template" type="text/html">
    {{# if (d && d.length > 0 ){ }}
    {{#  layui.each(d, function(index, item){ }}
    <div class="comment" comtid="{{ item.comtid }}" userid="{{ item.userid }}">
        <a class=" avatar">
            <img src="{{ item.criticAvatar }}"/>
        </a>
        <div class="content">
            <a href="javascript:" target="_blank" class="author">
                <span>{{ item.criticName }}</span>
            </a>
            <div class="metadata">
                <span class="date">{{ item.cretim }}</span>
            </div>
            <div class="text">{{ item.content }}</div>
            <div class="option">
                <i class="praise icon-dianzan iconfont {{# if(item.praiseStatus){ }} active {{# } }}" onclick="praiseHandle(this)">&nbsp;{{ item.prenum }}</i>
                &nbsp;&nbsp;<a href="#jump_comment" class="reply" onclick="commentReply(this)">回复</a>
            </div>
            {{# if(item.children && item.children.length > 0){ }}
            {{# layui.each(item.children, function(index, subItem){ }}
            <div class="comment" comtid="{{ subItem.comtid }}" userid="{{ subItem.userid }}">
                <a class="avatar">
                    <img src="{{ subItem.criticAvatar }}"/>
                </a>
                <div class="content">
                    <a href="javascript:" target="_blank" class="author">
                        <span>{{ subItem.criticName }}</span>
                    </a>
                    <div class="metadata">
                        <span>回复&nbsp; <a href="javascript:">@{{ subItem.replyCriticName }}</a></span>
                        <span class="date">{{ subItem.cretim }}</span>
                    </div>
                    <div class="text">{{ subItem.content }}</div>
                    <div class="option">
                        <i class="praise icon-dianzan iconfont" onclick="praiseHandle(this)">&nbsp;{{
                            subItem.prenum }}</i>
                        &nbsp;&nbsp;<a href="#jump_comment" class="reply" onclick="commentReply(this)">回复</a>
                    </div>
                </div>
            </div>
            {{# }); }}
            {{# } }}
        </div>
    </div>
    {{#  }); }}
    {{# } else { }}
    <span>暂无评论</span>
    {{# } }}
</script>
<script>
    let parentNode = {};
    layui.config({
        base: '../../module/'
    }).extend({
        tinymce: 'tinymce/tinymce',
    }).use(['config', 'index', 'admin', 'element', 'tinymce', 'form', 'laytpl'], () => {
        let config = layui.config,
            admin = layui.admin,
            tinymce = layui.tinymce,
            form = layui.form,
            laytpl = layui.laytpl;
        let currentUser = config.getUser();


        // 博文预览数据回显
        let articleTypeSelect = {};
        for (let item of admin.getTempData('articleTypeSelect')) articleTypeSelect[item['mtcode']] = item['mtname'];
        let articleData = admin.getTempData('t_article');
        $('.blog-info-title').text(articleData.atitle);
        $('.blog-info-author').text(articleData.author);
        $('.blog-info-type').text(articleTypeSelect[articleData.artype]);
        $('.blog-info-createTime').text(articleData.cretim);
        $('.blog-info-hits').append(articleData.arhits);
        $('.blog-info-collect').append(articleData.cetnum);
        $('.blog-info-content').html(articleData.content);
        appendBadgeToNode(articleData['artags'].split(','), '.blog-info-tags');
        appendBadgeToNode(articleData['catgry'].split(','), '.blog-info-category');

        function appendBadgeToNode(array, selector) {
            for (let item of array) $(selector).append('<span class="layui-badge-rim">' + item + '</span>');
        }

        // 加载评论
        admin.req('api-forum/comment/blogComment', {cobjid: articleData.arleid, userid: currentUser.id}, (res) => {
            console.log(res,1111);
            let data = res.data;
            let getTpl = comment_template.innerHTML,
                view = $('#comments-content');
            laytpl(getTpl).render(data, function (html) {
                view.append(html);
            });
        }, 'GET');

        //富文本编辑器渲染
        tinymce.render({
            elem: "#blogEditor"
            , height: 400
            , auto_focus: true
            , placeholder: '发条友善的评论',
            images_upload_handler: function (blobInfo, succFun, failFun) {
                let xhr, formData;
                let file = blobInfo.blob();//转化为易于理解的file对象
                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('POST', config.base_server + 'api-file/files-anon');
                xhr.setRequestHeader('Authorization', 'Bearer '.concat(config.getToken().access_token));
                xhr.onload = function () {
                    let json;
                    if (xhr.status !== 200) {
                        failFun('HTTP Error: ' + xhr.status);
                        return;
                    }
                    json = JSON.parse(xhr.responseText);
                    if (!json || typeof json.url != 'string') {
                        failFun('Invalid JSON: ' + xhr.responseText);
                        return;
                    }
                    succFun(json.url);
                };
                formData = new FormData();
                formData.append('file', file, file.name);
                xhr.send(formData);
            },
            init_instance_callback: () => {
                // 禁用 - 编辑器获取焦点、内容为空时的弹出框
                let tox_toolbar = $('.tox.tox-silver-sink.tox-tinymce-aux');
                tox_toolbar.bind('DOMNodeInserted', (e) => {
                    tox_toolbar.find('.tox-pop.tox-pop--left').css('display', 'none');
                });
            }
        });

        // 提交评论
        form.on('submit(submitCommnet)', () => {
            let editor = tinymce.get('#blogEditor');
            if (!editor.getContent()) {
                layer.msg('评论不能为空...', {icon: 2, time: 500});
                return $(editor.contentDocument.body).focus();
            }
            let params = admin.getTempData('t_blogComment') ? admin.getTempData('t_blogComment') : {};
            params.cobjid = articleData.arleid;
            params.userid = currentUser.id;
            params.content = editor.getContent();
            console.log(params);
            admin.req('api-forum/comment/blogComment', JSON.stringify(params), (res) => {
                if (res.code === 0) {
                    appendCommentToNode(res.data);  // 渲染添加的评论节点
                    editor.resetContent();          // 清空编辑器
                    $('.reply.active').removeClass('active');          // 移除回复激活样式
                    return admin.putTempData('t_blogComment', {}) && (parentNode = {}); // 清空临时存储
                }
                layer.msg('当前服务出现异常,请稍后重试...', {icon: 2, time: 500});
            }, 'POST');
        });

        // 添加评论到页面节点
        function appendCommentToNode(data) {
            // 当评论为二级评论
            if (data.pcomid && parseInt(data.pcomid) !== 0) {
                $($(parentNode).find('.content')[0]).append(commentTemplate(data));
                let replyTemplate = '<span>回复&nbsp; <a href="javascript:">@' + data.replyCriticName + '</a></span>';
                $("div[class='comment'][comtid='" + data.comtid + "']").find('.metadata').prepend(replyTemplate);
            } else {
                $('#comments-content').append(commentTemplate(data));
            }
        }

        // 评论节点模板
        function commentTemplate(data) {
            return `<div class="comment" comtid="` + data.comtid + `" userid="` + data.userid + `">
                <a class="avatar">
                    <img src=` + data.criticAvatar + `>
                </a>
                <div class="content">
                    <a href="javascript:" target="_blank" class="author">
                        <span>` + data.criticName + `</span>
                    </a>
                    <div class="metadata">
                        <!--<span>回复&nbsp; <a href="javascript:">@{{ subItem.replyCriticName }}</a></span>-->
                        <span class="date">` + data.cretim + `</span>
                    </div>
                    <div class="text">` + data.content + `</div>
                    <div class="option">
                        <i class="praise icon-dianzan iconfont"></i>
                        <span class="reply" onclick="commentReply(this)">回复</span>
                    </div>
                </div>
            </div>`;
        }
    });

    // 回复评论
    function commentReply(e) {
        $('.reply.active').removeClass('active');
        $(e).toggleClass('active');
        layui.use(['tinymce', 'admin'], () => {
            let tinymce = layui.tinymce, admin = layui.admin;
            parentNode = $(e).parents('.comment');
            admin.putTempData('t_blogComment', {
                recoid: parentNode.attr('comtid'),
                recuid: parentNode.attr('userid'),
                pcomid: parentNode.parents('.comment').length > 0 ? parentNode.parents('.comment').attr('comtid') : parentNode.attr('comtid'),
            });
            let editor = tinymce.get('#blogEditor');
            // 点击回复时的占位符提示
            let replyHint = '回复@' + $(parentNode[0]).find('.author>span')[0].innerText + ':';
            editor.resetContent();
            $(editor.contentDocument.body).attr('data-mce-placeholder', replyHint).focus();
        });
    }

    // 点赞处理
    function praiseHandle(e) {
        layui.use(['config', 'admin', 'layer'], () => {
            let userid = layui.config.getUser().id;
            let currentComment = $($(e).parents('.comment')[0]);
            $(e).toggleClass('active');
            layui.admin.req('api-forum/comment/praise', JSON.stringify({
                userid: userid,
                comtid: currentComment.attr('comtid'),
                praiseStatus: $(e).hasClass('active')
            }), (res) => {
                if (res.code === 0) {
                    return $(e).text(' ' + res.data);
                }
                layui.layer.msg('当前服务出现异常,请稍后重试...', {icon: 2, time: 500});
            }, 'POST');
        });
    }
</script>
</html>

